package com.itcam.tingshu.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.itcam.tingshu.account.client.UserAccountFeignClient;
import com.itcam.tingshu.album.client.AlbumInfoFeignClient;
import com.itcam.tingshu.album.client.TrackInfoFeignClient;
import com.itcam.tingshu.common.constant.KafkaConstant;
import com.itcam.tingshu.common.constant.SystemConstant;
import com.itcam.tingshu.common.execption.ItcamException;
import com.itcam.tingshu.common.result.Result;
import com.itcam.tingshu.common.result.ResultCodeEnum;
import com.itcam.tingshu.common.service.KafkaService;
import com.itcam.tingshu.model.album.AlbumInfo;
import com.itcam.tingshu.model.album.TrackInfo;
import com.itcam.tingshu.model.order.OrderDerate;
import com.itcam.tingshu.model.order.OrderDetail;
import com.itcam.tingshu.model.order.OrderInfo;
import com.itcam.tingshu.model.user.VipServiceConfig;
import com.itcam.tingshu.order.helper.SignHelper;
import com.itcam.tingshu.order.mapper.OrderDerateMapper;
import com.itcam.tingshu.order.mapper.OrderDetailMapper;
import com.itcam.tingshu.order.mapper.OrderInfoMapper;
import com.itcam.tingshu.order.service.OrderDetailService;
import com.itcam.tingshu.order.service.OrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcam.tingshu.user.client.UserInfoFeignClient;
import com.itcam.tingshu.vo.account.AccountLockResultVo;
import com.itcam.tingshu.vo.account.AccountLockVo;
import com.itcam.tingshu.vo.order.OrderDerateVo;
import com.itcam.tingshu.vo.order.OrderDetailVo;
import com.itcam.tingshu.vo.order.OrderInfoVo;
import com.itcam.tingshu.vo.order.TradeVo;
import com.itcam.tingshu.vo.user.UserInfoVo;
import com.itcam.tingshu.vo.user.UserPaidRecordVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;

    @Qualifier("com.itcam.tingshu.album.client.TrackInfoFeignClient")
    @Autowired
    private TrackInfoFeignClient trackInfoFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;
    @Qualifier("com.itcam.tingshu.account.client.impl.UserAccountFeignClient")
    @Autowired
    private UserAccountFeignClient userAccountFeignClient;

    @Autowired
    private KafkaService kafkaService;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderDerateMapper orderDerateMapper;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private RedissonClient redissonClient;


    /**
     * 订单结算页
     * @param tradeVo {"itemType":"1003","itemId":专辑ID【声音ID、VipServiceConfig.ID】}
     * @param userId
     * @return
     */
    @Override
    public OrderInfoVo trade(TradeVo tradeVo, Long userId) {
        // 创建对象
        OrderInfoVo orderInfoVo = new OrderInfoVo();

        // 声明局部变量
        // 订单原始金额
        BigDecimal originalAmount = new BigDecimal("0.00");
        // 减免总金额
        BigDecimal derateAmount = new BigDecimal("0.00");
        // 订单总金额
        BigDecimal orderAmount = new BigDecimal("0.00");
        // 订单明细集合
        List<OrderDetailVo> orderDetailVoList = new ArrayList<>();
        // 订单减免明细列表
        List<OrderDerateVo> orderDerateVoList = new ArrayList<>();

        // 根据用户id获取用户信息
        Result<UserInfoVo> userInfoVoResult = userInfoFeignClient.getUserInfoVo(userId);
        Assert.notNull(userInfoVoResult, "返回用户信息结果集为空");
        UserInfoVo userInfoVo = userInfoVoResult.getData();
        Assert.notNull(userInfoVo, "用户信息为空");
        // 判断购买类型
        if (tradeVo.getItemType().equals(SystemConstant.ORDER_ITEM_TYPE_ALBUM)) {
            // 购买专辑
            Result<Boolean> isPaidAlbumResult = this.userInfoFeignClient.isPaidAlbum(tradeVo.getItemId());
            // 判断是否为空
            Assert.notNull(isPaidAlbumResult, "购买专辑结果集为空");
            Boolean result = isPaidAlbumResult.getData();
            // result=true 说明购买过了
            if (result) {
                throw new ItcamException(ResultCodeEnum.REPEAT_BUY_ERROR);
            }
            // 判断当前专辑是否参与折扣
            Result<AlbumInfo> albumInfoResult = albumInfoFeignClient.getAlbumInfo(tradeVo.getItemId());
            Assert.notNull(albumInfoResult, "专辑结果集为空");
            AlbumInfo albumInfo = albumInfoResult.getData();
            Assert.notNull(albumInfo, "专辑信息为空");
            // 没有购买过 —— 第一次购买专辑 —— 需要计算出各种金额，以及订单明细和减免明细
            // 判断当前用户是否为vip —— 根据用户Id获取到用户信息判断
            if (userInfoVo.getIsVip() == 0) {
                // 计算普通用户的订单金额
                originalAmount = albumInfo.getPrice();
                // 判断是否打折
                if (albumInfo.getDiscount().compareTo(new BigDecimal("-1")) != 0) {
                    // 1000->八折->800 减免200
                    // 方案一：减免金额：1000-(1000*8/10)=200
                    // derateAmount = originalAmount.subtract(originalAmount.multiply(albumInfo.getDiscount()).divide(new BigDecimal("10")));
                    // 方案二：减免金额：1000*(10-8.8)/10=120
                    orderAmount = originalAmount.multiply(new BigDecimal("10").subtract(albumInfo.getDiscount())).divide(new BigDecimal("10"), 2, BigDecimal.ROUND_HALF_UP);
                }
                // 订单总价
                orderAmount = originalAmount.subtract(derateAmount);
            } else {
                // 订单原始金额
                originalAmount = albumInfo.getPrice();
                // 判断是否打折
                if (albumInfo.getVipDiscount().compareTo(new BigDecimal("-1")) != 0) {
                    orderAmount = originalAmount.multiply(new BigDecimal("10").subtract(albumInfo.getVipDiscount())).divide(new BigDecimal("10"), 2, BigDecimal.ROUND_HALF_UP);
                }
                // 订单总价
                orderAmount = originalAmount.subtract(derateAmount);
            }
            // 订单明细
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            orderDetailVo.setItemId(tradeVo.getItemId());
            orderDetailVo.setItemPrice(orderAmount);
            orderDetailVo.setItemUrl(albumInfo.getCoverUrl());
            orderDetailVo.setItemName(albumInfo.getAlbumTitle());
            orderDetailVoList.add(orderDetailVo);
            // 减免明细
            if (derateAmount.compareTo(new BigDecimal("0.00")) != 0) {
                OrderDerateVo orderDerateVo = new OrderDerateVo();
                orderDerateVo.setDerateAmount(derateAmount);
                orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_ALBUM_DISCOUNT);
                orderDerateVo.setRemarks("专辑折扣");
                orderDerateVoList.add(orderDerateVo);
            }
        } else if (tradeVo.getItemType().equals(SystemConstant.ORDER_ITEM_TYPE_TRACK)) {
            // 购买声音
            // 判断用户购买的声音集数，如果<0说明用户篡改数据
            if (tradeVo.getTrackCount() < 0) {
                throw new ItcamException(ResultCodeEnum.DATA_ERROR);
            }
            // 购买集数 >= 0 ;等于0的时候购买本机 > 0 的时候购买了多集
            Result<List<TrackInfo>> trackInfoListResult = trackInfoFeignClient.findPaidTrackInfoList(tradeVo.getItemId(), tradeVo.getTrackCount());
            Assert.notNull(trackInfoListResult, "购买声音集合列表为空");
            List<TrackInfo> trackInfoList = trackInfoListResult.getData();
            Assert.notNull(trackInfoList, "购买声音集合为空");
            Result<AlbumInfo> albumInfoResult = this.albumInfoFeignClient.getAlbumInfo(trackInfoList.get(0).getAlbumId());
            Assert.notNull(albumInfoResult, "专辑信息为空");
            AlbumInfo albumInfo = albumInfoResult.getData();
            Assert.notNull(albumInfo, "专辑对象为空");
            // 赋值订单金额：原始金额【单价=albumInfo.price】，订单金额，声音不包含折扣
            originalAmount = tradeVo.getTrackCount() != 0 ? albumInfo.getPrice().multiply(new BigDecimal(String.valueOf(tradeVo.getTrackCount()))) : albumInfo.getPrice();
            orderAmount = originalAmount;
            // 赋值订单明细，没有减免明细
            orderDetailVoList = trackInfoList.stream().map(trackInfo -> {
                // 创建对象
                OrderDetailVo orderDetailVo = new OrderDetailVo();
                // 赋值
                orderDetailVo.setItemId(trackInfo.getId());
                orderDetailVo.setItemName(trackInfo.getTrackTitle());
                orderDetailVo.setItemUrl(trackInfo.getCoverUrl());
                orderDetailVo.setItemPrice(albumInfo.getPrice());
                return orderDetailVo;
            }).collect(Collectors.toList());
        } else {
            // 购买vip —— {"itemType":"1003","itemId":2}
            // 赋值：金额+订单明细+减免明细
            Long vipServiceConfigId = tradeVo.getItemId();
            Result<VipServiceConfig> vipServiceConfigResult = this.userInfoFeignClient.getVipServiceConfig(tradeVo.getItemId());
            // 判断
            Assert.notNull(vipServiceConfigResult, "vip服务配置信息结果集为空");
            VipServiceConfig vipServiceConfig = vipServiceConfigResult.getData();
            Assert.notNull(vipServiceConfig, "vip服务配置对象为空");
            // 获取原始价格
            originalAmount = vipServiceConfig.getPrice();
            // 实际价格
            orderAmount = vipServiceConfig.getDiscountPrice();
            // 减免金额
            derateAmount = originalAmount.subtract(orderAmount);
            // 订单明细
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            orderDetailVo.setItemId(tradeVo.getItemId());
            orderDetailVo.setItemName(vipServiceConfig.getName());
            orderDetailVo.setItemUrl(vipServiceConfig.getImageUrl());
            orderDetailVo.setItemPrice(orderAmount);
            orderDetailVoList.add(orderDetailVo);
            // 减免明细
            if (orderAmount.compareTo(new BigDecimal("0.00")) != 0) {
                OrderDerateVo orderDerateVo = new OrderDerateVo();
                orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_VIP_SERVICE_DISCOUNT);
                orderDerateVo.setDerateAmount(derateAmount);
                orderDerateVo.setRemarks("vip折扣");
                orderDerateVoList.add(orderDerateVo);
            }
        }
        // 给对象赋值
        String tradeNo = UUID.randomUUID().toString().replace("--", "");
        // 防止用户重复提交订单！
        String key = "tradeNO:" + userId; // 如果是多平台——>String key = "tradeNO:" + userId + tradeNo;
        // setnx + setex;
        this.redisTemplate.opsForValue().setIfAbsent(key, tradeNo, 120, TimeUnit.SECONDS);
        // 设置tradeNo
        orderInfoVo.setTradeNo(tradeNo);
        orderInfoVo.setPayWay("");
        orderInfoVo.setItemType(tradeVo.getItemType());
        orderInfoVo.setOriginalAmount(originalAmount);
        orderInfoVo.setDerateAmount(derateAmount);
        orderInfoVo.setOrderAmount(orderAmount);
        orderInfoVo.setOrderDetailVoList(orderDetailVoList);
        orderInfoVo.setOrderDerateVoList(orderDerateVoList);
        // 设置时间戳
        orderInfoVo.setTimestamp(SignHelper.getTimestamp());
        // 签名 —— 保障数据的完整性，防止用户篡改数据
        //  OrderInfo-->String-->Map-->sign
        //  {1.除去sign参数 2.将map进行排序 3.将map中的值使用|进行拼接得到一个新的字符串 4.在新的字符串后面+盐[固定字符串] 5.将最新字符串进行md5加密返回}
        // 1.将OrderInfoVo转为字符串
        String jsonStr = JSON.toJSONString(orderInfoVo);
        // 2.再转为map
        Map<String, Object> parameterMap = JSON.parseObject(jsonStr, Map.class);
        // 3.通过工具类SignHelper将map转为字符串
        String sign = SignHelper.getSign(parameterMap);
        orderInfoVo.setSign(sign);

        // 返回数据
        return orderInfoVo;
    }

    /**
     * 提交订单
     * @param orderInfoVo
     * @param userId
     * @return
     */
    @Override
    public String submitOrder(OrderInfoVo orderInfoVo, Long userId) {
        // 校验签名与流水号
        // 签名怎么来的？ 1.除去sign参数 2.将map进行排序 3.将map中的值使用|进行拼接得到一个新的字符串 4.在新的字符串后面+盐[固定字符串] 5.将最新字符串进行md5加密返回
        Map map = JSON.parseObject(JSON.toJSONString(orderInfoVo), Map.class);
        // orderInfoVo.setPayWay("");前端传递时payWay：“1103”
        map.put("payWay", "");
        // 调用工具类方法
        SignHelper.checkSign(map);
        // 获取页面的流水号
        String tradeNo = orderInfoVo.getTradeNo();
        // 获取redis流水号
        String key = "tradeNo:" + userId + tradeNo;
        // 获取缓存中的流水号
        // String redisTradeNo = (String) this.redisTemplate.opsForValue().get(key);
        // if (!redisTradeNo.equals(tradeNo)) {
        //     // 抛出异常
        //     throw new ItcamException(ResultCodeEnum.REPEAT_BUY_ERROR);
        // }

        // 判断key是否存在，setnx+setex
        // Boolean result = this.redisTemplate.opsForValue().setIfAbsent(key, tradeNo, 10, TimeUnit.SECONDS);
        // if (!result) {
        //     throw new ItcamException(ResultCodeEnum.REPEAT_BUY_ERROR);
        // }

        // 为了防止多线程误删，优化为lua脚本
        // 定义lua脚本
        String scriptText = "if redis.call(\"get\",KEYS[1] == ARGV[1]\n" +
                "then\n" +
                "   return redis.call(\"del\",KEYS[1]\n" +
                "else\n" +
                "   return 0\n" +
                "end";
        DefaultRedisScript<Long> script = new DefaultRedisScript<>();
        script.setScriptText(scriptText);
        script.setResultType(Long.class);
        Long count = (Long) this.redisTemplate.execute(script, Arrays.asList(key), tradeNo);
        if (count == 0) {
            // 抛出异常
            throw new ItcamException(ResultCodeEnum.REPEAT_BUY_ERROR);
        }
        // 声明一个orderNo订单编号
        String orderNo = UUID.randomUUID().toString().replaceAll("-", "");
        // 判断当前的支付方式
        if (!orderInfoVo.getPayWay().equals(SystemConstant.ORDER_PAY_ACCOUNT)) {
            // 在线支付
            this.saveOrder(orderInfoVo, userId, orderNo);
        } else {
            // 余额支付
            // 检查是否有足够的余额，需要锁定余额
            AccountLockVo accountLockVo = new AccountLockVo();
            accountLockVo.setUserId(userId);
            accountLockVo.setAmount(orderInfoVo.getOrderAmount());
            accountLockVo.setOrderNo(orderNo);
            accountLockVo.setContent("余额支付锁定.");
            try {
                // 远程调用方法，检查与锁定
                Result<AccountLockResultVo> result = userAccountFeignClient.checkAndLock(accountLockVo);
                if (result.getCode() != ResultCodeEnum.SUCCESS.getCode()) {
                    // 抛出异常
                    throw new ItcamException(result.getCode(), result.getMessage());
                }
                // 保存订单，保存用户购买记录
                this.saveOrder(orderInfoVo, userId, orderNo);
                // 真正扣减金额
                kafkaService.sendMsg(KafkaConstant.QUEUE_ACCOUNT_MINUS, orderNo);
            } catch (ItcamException e) {
                // 如果出现了异常，则需要将金额加回去
                kafkaService.sendMsg(KafkaConstant.QUEUE_ACCOUNT_UNLOCK, orderNo);
                throw new RuntimeException(e);
            }
        }

        // 返回订单编号
        return orderNo;
    }

    /**
     * 订单取消
     * @param l
     */
    @Override
    public void orderCancel(long orderId) {
        // 更新订单状态
        OrderInfo orderInfo = this.getById(orderId);
        // 当订单未支付的时候，取消订单
        if (null != orderInfo && orderInfo.getOrderStatus().equals(SystemConstant.ORDER_STATUS_UNPAID)) {
            // 修改订单状态
            orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_CANCEL);
            orderInfo.setUpdateTime(new Date());
            // 执行更新方法
            orderInfoMapper.updateById(orderInfo);
        }
    }

    /**
     * 根据订单编号获取订单对象
     * @param orderNo
     * @return
     */
    @Override
    public OrderInfo getOrderInfo(String orderNo) {
        // 调用方法
        OrderInfo orderInfo = this.getOrderInfoByOrderNo(orderNo);
        // 需要将支付方式由编号变为文字，“1103”
        orderInfo.setPayWayName(this.getPayWayName(orderInfo.getPayWay()));
        // 返回数据
        return orderInfo;
    }


    /**
     * 查看我的订单
     * @param pageParam
     * @param userId
     * @return
     */
    @Override
    public IPage<OrderInfo> findUserPage(Page<OrderInfo> pageParam, Long userId, String orderStatus) {
        // 调用mapper层方法
        IPage<OrderInfo> infoIPage = orderInfoMapper.selectUserPage(pageParam, userId, orderStatus);
        infoIPage.getRecords().stream().forEach(orderInfo -> {
            orderInfo.setOrderStatusName(this.getOrderStatusNameByOrderStatus(orderInfo.getOrderStatus()));
        });

        return infoIPage;
    }


    // --------------------------------------------------------------------------------------------------

    /**
     * 获取订单状态名称
     * @param orderStatus
     * @return
     */
    private String getOrderStatusNameByOrderStatus(String orderStatus) {
        //  根据状态获取状态名称
        switch (orderStatus) {
            case "0901":
                return "未支付";
            case "0902":
                return "已支付";
            case "0903":
                return "已取消";
            default:
                return null;
        }
    }

    /**
     * 根据数字编号查询支付方式
     * @param payWay
     * @return
     */
    private String getPayWayName(String payWay) {
        // 余额、支付宝、微信
        switch (payWay) {
            case "1101":
                return "微信";
            case "1102":
                return "支付宝";
            case "1103":
                return "余额";
            default:
                return null;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    private void saveOrder(OrderInfoVo orderInfoVo, Long userId, String orderNo) {
        // 保存数据 order_info order_detail order_derate
        // 三张表保存操作涉及到事务 ——> 事务失效问题
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(orderInfoVo, orderInfo);
        // 赋值userId
        orderInfo.setUserId(userId);
        orderInfo.setOrderNo(orderNo);
        orderInfo.setOrderTitle(orderInfoVo.getOrderDetailVoList().get(0).getItemName());
        orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_UNPAID);
        orderInfoMapper.insert(orderInfo);
        // 保存订单明细
        List<OrderDetailVo> orderDetailVoList = orderInfoVo.getOrderDetailVoList();
        // if (CollectionUtils.isEmpty(orderDetailVoList)) {
        //     orderDetailVoList.stream()
        //             .forEach(orderDetailVo -> {
        //                 // 创建一个订单明细对象
        //                 OrderDetail orderDetail = new OrderDetail();
        //                 BeanUtils.copyProperties(orderDetailVo, orderDetail);
        //                 orderDetail.setOrderId(orderInfo.getId());
        //                 // 保存数据
        //                 orderDetailMapper.insert(orderDetail);
        //             });
        // }
        // 优化为批量保存
        if (!CollectionUtils.isEmpty(orderDetailVoList)) {
            List<OrderDetail> orderDetailList = orderDetailVoList.stream()
                    .map(orderDetailVo -> {
                        OrderDetail orderDetail = new OrderDetail();
                        BeanUtils.copyProperties(orderDetailVo, orderDetail);
                        orderDetail.setOrderId(orderInfo.getId());
                        return orderDetail;
                    }).collect(Collectors.toList());
            // 批量保存 —— Iservice ServiceImpl
            boolean result = orderDetailService.saveBatch(orderDetailList);
            if (!result) {
                throw new ItcamException(555, "保存订单明细失败");
            }
        }
        // 减免表
        List<OrderDerateVo> orderDerateVoList = orderInfoVo.getOrderDerateVoList();
        if (!CollectionUtils.isEmpty(orderDerateVoList)) {
            orderDetailVoList.stream().forEach(orderDerateVo -> {
                // 创建对象
                OrderDerate orderDerate = new OrderDerate();
                BeanUtils.copyProperties(orderDerateVo, orderDerate);
                orderDerate.setOrderId(orderInfo.getId());
                // 保存数据
                orderDerateMapper.insert(orderDerate);
            });
        }
        // 判断支付类型，记录当前用户购买记录信息
        if (orderInfoVo.getPayWay().equals(SystemConstant.ORDER_PAY_ACCOUNT)) {
            // 余额支付
            // orderPaySuccess(orderNo); 区分类型：1001-专辑，1002-声音，1003-vip会员 知道具体购买的vipid，albumId,trackId;保存到对应的表中
            this.orderPaySuccess(orderNo);
        } else {
            // 在线支付
            // 发送一个延迟消息，判断在规定的时间内是否进行了付款，如果没有付款则取消订单
            this.sendDelayMessage(orderInfo.getId());
        }
    }

    /**
     * 发送延迟消息
     * @param id
     */
    private void sendDelayMessage(Long orderId) {
        // redissonClient发送
        try {
            // 创建一个阻塞队列
            RBlockingDeque<Object> blockingDeque = this.redissonClient.getBlockingDeque(KafkaConstant.QUEUE_ORDER_CANCEL);
            // 获取延迟队列
            RDelayedQueue<Object> delayedQueue = this.redissonClient.getDelayedQueue(blockingDeque);
            // 向队列中存储数据
            delayedQueue.offer(orderId.toString(), KafkaConstant.DELAY_TIME, TimeUnit.SECONDS);
            log.info("添加延时队列成功 ，延迟时间：{}，订单id：{}", KafkaConstant.DELAY_TIME, orderId);
        } catch (Exception e) {
            log.error("添加延时队列失败 ，延迟时间：{}，订单id：{}", KafkaConstant.DELAY_TIME, orderId);
            e.printStackTrace();
        }

    }

    /**
     * 订单支付成功
     * @param orderNo
     */
    @Override
    public void orderPaySuccess(String orderNo) {
        // 根据orderNo获取到订单对象
        OrderInfo orderInfo = this.getOrderInfoByOrderNo(orderNo);
        orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_PAID);
        orderInfo.setUpdateTime(new Date());
        // 更新订单状态
        this.orderInfoMapper.updateById(orderInfo);
        // 区分购买类型 以发送消息的形式让用户微服务处理
        // UserPaidRecordVo userPaidRecordVo = new UserPaidRecordVo();
        // userPaidRecordVo.setOrderNo(orderNo);
        // userPaidRecordVo.setUserId(orderInfo.getUserId());
        // userPaidRecordVo.setItemType(orderInfo.getItemType());
        // 购买的Id：专辑Id、声音Id、VIP会员Id
        // List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        // List<Long> itemIdList = orderDetailList.stream()
        //         .map(OrderDetail::getItemId)
        //         .collect(Collectors.toList());
        // userPaidRecordVo.setItemIdList(itemIdList);
        // 发送消息
        // kafkaService.sendMsg(KafkaConstant.QUEUE_USER_PAY_RECORD, JSON.toJSONString(userPaidRecordVo));
    }

    /**
     * 根据订单编号查询订单信息
     * @param orderNo
     * @return
     */
    private OrderInfo getOrderInfoByOrderNo(String orderNo) {
        // 构建查询条件
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo));
        // 根据订单id查询你订单明细
        if (null != orderInfo) {
            List<OrderDetail> orderDetailList = orderDetailMapper.selectList(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId, orderInfo.getId()));
        }
        // 返回数据
        return orderInfo;
    }


}




























